namespace LightBox.Flickr.Providers
{
	using System;
	
	using Properties;

	public class FlickrConnection
	{
		const string ApiKeyString = "APIKEY";
		const string SharedSecretString = "SHAREDSECRET";
		const string UsernameString = "USERNAME";

		private string apiKey;
		private string sharedSecret;
		private string userName;

		public FlickrConnection(string connectionString)
		{
			if (string.IsNullOrEmpty(connectionString))
			{
				throw new ArgumentNullException("connectionString",
					"Connection string cannot be null.");
			}

			Parse(connectionString);
		}

		public string ApiKey
		{
			get { return apiKey; }
		}

		public string Secret
		{
			get { return sharedSecret; }
		}

		public string Username
		{
			get { return userName; }
		}

		private void Parse(string connString)
		{
			string[] items = connString.Split(';');

			if (items != null)
			{
				foreach (string item in items)
				{
					ParseKey(item);
				}
			}
			else
			{
				ThrowInvalidConnectionStringFormatException();
			}
		}

		private void ParseKey(string item)
		{
			string[] parts = item.Split('=');

			if (parts != null && (parts.Length == 2))
			{
				string key = parts[0];

				switch (key.Trim().ToUpper())
				{
					case ApiKeyString:
						this.apiKey = parts[1];
						break;

					case SharedSecretString:
						this.sharedSecret = parts[1];
						break;

					case UsernameString:
						this.userName = parts[1];
						break;
				}
			}
			else
			{
				ThrowInvalidConnectionStringFormatException();
			}
		}

		private void ThrowInvalidConnectionStringFormatException()
		{
			throw new InvalidOperationException(Resources.ExceptionConnectionStringFormat);
		}
	}
}
